package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class ManageServiceImpl implements ManageService {


    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;

    @Autowired
    private RabbitService rabbitService;


    @Override
    public List<BaseCategory1> getAllBaseCategory1() {
        return baseCategory1Mapper.selectList(null);
    }


    /**
     * 获取一级分类
     *
     * @param category1Id
     * @return
     */
    @Override
    public List<BaseCategory2> getAllBaseCategory2(Long category1Id) {

//        根据一级分类id获取二级分类
        QueryWrapper<BaseCategory2> wrapper = new QueryWrapper<>();
        wrapper.eq("category1_id", category1Id);
        return baseCategory2Mapper.selectList(wrapper);

    }

    /**
     * 获取二级分类
     *
     * @param category2Id
     * @return
     */
    @Override
    public List<BaseCategory3> getAllBaseCategory3(Long category2Id) {
        //        根据二级分类id获取三级分类
        QueryWrapper<BaseCategory3> wrapper = new QueryWrapper<>();
        wrapper.eq("category2_id", category2Id);
        return baseCategory3Mapper.selectList(wrapper);
    }

    /**
     * 根据分类id获取平台属性和平台属性值数据
     *
     * @param category1Id
     * @return
     */
    @Override
    @GmallCache(prefix = "BaseAttrInfo")
    public List<BaseAttrInfo> getAllBaseAttrInfo(Long category1Id, Long category2Id, Long category3Id) {

//        根据分裂id获取属性
        return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id, category2Id, category3Id);
    }


    //    保存平台属性或者修改平台属性
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
//        判断保存或者修改数据
        if (baseAttrInfo.getId() != null) {
//                修改数据
            baseAttrInfoMapper.updateById(baseAttrInfo);
        } else {
//        保存属性表
            baseAttrInfoMapper.insert(baseAttrInfo);
        }

//        不知道是修改还是新增删除属性值表对应的id数据
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id", baseAttrInfo.getId());
        baseAttrValueMapper.delete(wrapper);

//          保存属性值表
        List<BaseAttrValue> valueList = baseAttrInfo.getAttrValueList();

        if (!CollectionUtils.isEmpty(valueList)) {
            for (BaseAttrValue baseAttrValue : valueList) {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }
    }

    //    根据平台属性值id获取属性值
    public List<BaseAttrValue> getBaseAttrValue(Long attrId) {

        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId));
    }


    //    根据id获取属性名称
    @Override
    public BaseAttrInfo getAttValues(Long attrId) {

        BaseAttrInfo baseAttrInfo;

//        获取属性名称
         baseAttrInfo = baseAttrInfoMapper.selectById(attrId);

        if (baseAttrInfo != null) {
            baseAttrInfo.setAttrValueList(getBaseAttrValue(attrId));
        }
        return baseAttrInfo;
    }


    //    根据三级分类id查询商品列表
    @Override
    public IPage<SpuInfo> getSpuInfoPage(Page<SpuInfo> pageInfo, SpuInfo spuInfo) {

        QueryWrapper<SpuInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("category3_id", spuInfo.getCategory3Id());

//        从大到小降序排序
        wrapper.orderByDesc("id");

        IPage<SpuInfo> infoIPage = spuInfoMapper.selectPage(pageInfo, wrapper);


        return infoIPage;
    }

    /**
     * 获取销售属性集合
     *
     * @return
     */
    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }


    //    添加spuInfo
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
//        spuInfo 商品表
        spuInfoMapper.insert(spuInfo);
//        spuImage 商品图片表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (spuImageList != null && spuImageList.size() > 0) {
            for (SpuImage spuImage : spuImageList) {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }
//        spuSaleAttr 销售属性表
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (spuSaleAttrList != null && spuSaleAttrList.size() > 0) {
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);

                //        spuSaleAttrValue 销售属性值表
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (spuSaleAttrValueList != null && spuSaleAttrValueList.size() > 0) {
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }
            }
        }

    }


    /**
     * 回显spu图片
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        QueryWrapper<SpuImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id", spuId);
        return spuImageMapper.selectList(queryWrapper);
    }

    //    根据spuId 查询销售属性集合
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    //    保存skuinfo消息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
//        保存skuInfo信息表
        skuInfoMapper.insert(skuInfo);

//        保存平台属性和skuAttvalue表
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            for (SkuAttrValue skuAttrValue : skuAttrValueList) {
//                补全skuId
                skuAttrValue.setSkuId(skuInfo.getId());
                skuAttrValueMapper.insert(skuAttrValue);
            }
        }
//        保存平台销售属性值信息表
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            for (SkuSaleAttrValue skuSaleAttrValue : skuSaleAttrValueList) {
//                补充skuId，spuId
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            }
        }

//        保存skuImages表
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)) {

            for (SkuImage skuImage : skuImageList) {
//                填充skuid
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            }
        }
    }

    /**
     * sku分页列表查询
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<SkuInfo> getPage(Page<SkuInfo> pageParam) {
        QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        IPage<SkuInfo> page = skuInfoMapper.selectPage(pageParam, queryWrapper);
        return page;
    }


    /**
     * 商品上架
     *
     * @param skuId
     */
    @Override
    public void onSale(Long skuId) {
        // 更改销售状态
        SkuInfo skuInfoUp = new SkuInfo();
        skuInfoUp.setId(skuId);
        skuInfoUp.setIsSale(1);
        skuInfoMapper.updateById(skuInfoUp);

//        发送消息到list服务实现商品上架
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    /**
     * 商品下架
     *
     * @param skuId
     */
    @Override
    public void cancelSale(Long skuId) {
        // 更改销售状态
        SkuInfo skuInfoUp = new SkuInfo();
        skuInfoUp.setId(skuId);
        skuInfoUp.setIsSale(0);
        skuInfoMapper.updateById(skuInfoUp);
//发送消息到list服务实现商品下架
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);

    }


    //    根据skuId获取skuInfo信息
    @Override
    @GmallCache(prefix = "skuInfo")
    public SkuInfo getSkuInfo(Long skuId) {

//        使用redis解决并发
//        return getRedisSkuInfo(skuId);

//        使用redisson解决分布式锁
//        getRedissonSkuIbfo(skuId);

        return getRedissonSkuIbfo(skuId);
    }

    //redisson
    private SkuInfo getRedissonSkuIbfo(Long skuId) {
        SkuInfo skuInfo = null;
        String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
//              redis中获取数据
        try {
            skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);

            if (skuInfo == null) {
                //            查询数据库
                //            加锁防止出现缓存击穿
                String skuInfoLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
                RLock lock = redissonClient.getLock(skuInfoLock);
                //            第一个参数尝试等待时间，第二个参数过期时间
                boolean flag = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
                //            拿到锁
                if (flag) {
                    try {
                        //                查询数据库数据
                        SkuInfo skuInfoValue = getSkuInfoDB(skuId);
                        if (skuInfoValue == null) {
                            //                    返回null
                            redisTemplate.opsForValue().set(skuKey, skuInfoValue, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                            return skuInfoValue;
                        }
                        //                    有数据，存入redis
                        redisTemplate.opsForValue().set(skuKey, skuInfoValue, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfoValue;

                    } finally {
                        lock.unlock();
                    }

                } else {
//                    没有拿到锁，进行自旋
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {


                        e.printStackTrace();
                    }
                    return getSkuInfo(skuId);
                }
            }
//                直接返回数据
            return skuInfo;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        出现异常查询数据库
        return getSkuInfoDB(skuId);
    }


    //        使用redis解决并发
    private SkuInfo getRedisSkuInfo(Long skuId) {
        /**
         * 使用redis实现并发处理解决缓存击穿
         */
        SkuInfo skuInfo = null;

        String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;

//        配置类中已经序列化过
        try {
            skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);

//        判断数据是否为空
            if (skuInfo == null) {

                //            加锁防止出现缓存击穿
                String skuInfoLock = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
                String uuid = UUID.randomUUID().toString();
                Boolean flag = redisTemplate.opsForValue()
                        .setIfAbsent(skuInfoLock, uuid, RedisConst.SECKILL__TIMEOUT, TimeUnit.SECONDS);
                //            拿到锁
                if (flag) {
                    //        查询数据库
                    SkuInfo skuInfoValue = getSkuInfoDB(skuId);
                    //            防止缓存穿透，返回空对象
                    if (skuInfoValue == null) {
                        redisTemplate.opsForValue().set(skuKey, skuInfoValue, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfoValue;
                    }
                    //                把数据存入redis中
                    redisTemplate.opsForValue().set(skuKey, skuInfoValue, RedisConst.SECKILL__TIMEOUT, TimeUnit.SECONDS);
                    //                    释放锁
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    redisScript.setScriptText(script);
                    redisScript.setResultType(Long.class);
                    redisTemplate.execute(redisScript, Arrays.asList(skuInfoLock), uuid);

                    return skuInfoValue;
                }
            } else {
                //        数据不为空直接返回数据
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
//            出现异常再次查询数据库
        }
        return getSkuInfoDB(skuId);
    }

    //          查询商品详情信息
    private SkuInfo getSkuInfoDB(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        // 根据skuId 查询图片列表集合
        QueryWrapper<SkuImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sku_id", skuId);
        List<SkuImage> skuImageList = skuImageMapper.selectList(queryWrapper);

        if (CollectionUtils.isNotEmpty(skuImageList)) {
            skuInfo.setSkuImageList(skuImageList);
        }

        return skuInfo;
    }


    /**
     * 根据三级分类id获取商品信息
     *
     * @param category3Id
     * @return
     */
    @Override
    @GmallCache(prefix = "CategoryViewByCategory3Id")
    public BaseCategoryView getCategoryViewByCategory3Id(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }


    /**
     * 获取sku价格
     *
     * @param skuId
     * @return
     */
    @Override
    @GmallCache(prefix = "skuPrice")
    public BigDecimal getSkuPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (null != skuInfo) {
            return skuInfo.getPrice();
        }
        return new BigDecimal("0");
    }


    //        根据skuId和spuId确定商品获取属性和属性值
    @Override
    @GmallCache(prefix = "SpuSaleAttrListCheckBySku")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId, spuId);
    }


    //    根据spuId 查询map 集合属性,即商品详情页面信息
    @Override
    @GmallCache(prefix = "SkuValueIdsMap")
    public Map getSkuValueIdsMap(Long spuId) {
// key = 125|123 ,value = 37
//        获取销售属性值信息
        List<Map> mapList = skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        Map<Object, Object> mapResult = new HashMap();
        if (mapList != null && mapList.size() > 0) {
            for (Map map : mapList) {
//             key = 125|123 ,value = 37   114|115 37    119|120 40
                mapResult.put(map.get("value_ids"), map.get("sku_id"));
            }
        }
        return mapResult;
    }

    //    获取首页分类数据一级分类，二级分类，三级分类
    @Override
    public List<JSONObject> getBaseCategoryList() {

//            用于最终的封装数据返回
        ArrayList<JSONObject> list = new ArrayList<>();
        // 获取视图所有分类数据
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        // 一级分类Id 进行分组
        Map<Long, List<BaseCategoryView>> category1Map  = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        int index = 1;
        // 获取一级分类的所有数据
        for (Map.Entry<Long, List<BaseCategoryView>> entry1  : category1Map.entrySet()) {
            // 获取一级分类Id
            Long category1Id  = entry1.getKey();
            // 获取一级分类的所有数据
            List<BaseCategoryView> category2List1  = entry1.getValue();
            //
            JSONObject category1 = new JSONObject();
            category1.put("index", index);
            category1.put("categoryId",category1Id);
            // 一级分类名称
            category1.put("categoryName",category2List1.get(0).getCategory1Name());
            // 变量迭代
            index++;


            // 循环获取二级分类数据
            Map<Long, List<BaseCategoryView>> category2Map  = category2List1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            // 声明二级分类对象集合
            List<JSONObject> category2Child = new ArrayList<>();
            // 循环遍历
            for (Map.Entry<Long, List<BaseCategoryView>> entry2  : category2Map.entrySet()) {
                // 获取二级分类Id
                Long category2Id  = entry2.getKey();
                // 获取二级分类下的所有集合
                List<BaseCategoryView> category3List  = entry2.getValue();
                // 声明二级分类对象
                JSONObject category2 = new JSONObject();

                category2.put("categoryId",category2Id);
                category2.put("categoryName",category3List.get(0).getCategory2Name());
                // 添加到二级分类集合
                category2Child.add(category2);

                List<JSONObject> category3Child = new ArrayList<>();

                // 循环三级分类数据
                category3List.stream().forEach(category3View -> {
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId",category3View.getCategory3Id());
//                    三级分类名称不重复
                    category3.put("categoryName",category3View.getCategory3Name());

                    category3Child.add(category3);
                });

                // 将三级数据放入二级里面
                category2.put("categoryChild",category3Child);

            }
            // 将二级数据放入一级里面
            category1.put("categoryChild",category2Child);
            list.add(category1);
        }
        return list;
 }


    /**
     * 查询品牌信息
     * @param tmId
     * @return
     */
    @Override
    public BaseTrademark getTrademarkByTmId(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }


    /**
     *根据skuid查询平台属性和平台属性值
     * @param skuId
     * @return
     */
    @Override
    public List<BaseAttrInfo> getAttrList(Long skuId) {

        return baseAttrInfoMapper.selectBaseAttrInfoListBySkuId(skuId);
    }


}
